<!-- @format -->

<template>
  <van-action-sheet
    v-model:show="visible"
    title="协议签署"
  >
    <div class="signature">
      <van-signature
        @submit="clickSubmit"
        @clear="clickClear"
      />
    </div>
  </van-action-sheet>
</template>

<script setup>
import { ref, onMounted, toRefs, inject } from 'vue'
import axios from 'axios'
import CORSSDK from 'cos-js-sdk-v5'
import { showToast } from 'vant'

const props = defineProps({
  meetingId: {
    type: String,
    default: '',
  },
  speakerId: {
    type: String,
    default: '',
  }
})
const emits = defineEmits(['submit'])
const api = inject('api');
const corsConfig = {
  bucket: 'projectimg-1256680128' /* 填入您自己的存储桶，必须字段 */,
  region: 'ap-beijing' /* 存储桶所在地域，例如ap-beijing，必须字段 */,
  key: 'lpm/' /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
}

const cors = ref();
const visible = ref(false)

function init() {
  visible.value = true
}

function uuid() {
  var s = []
  var hexDigits = '0123456789abcdefghi'
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'

  var uuid = s.join('')
  return uuid
}

function dataURLtoBlob (dataurl) {
   const arr = dataurl.split(',');
   const mime = arr[0].match(/:(.*?);/)[1];
   const bstr = atob(arr[1]);
   let n = bstr.length;
   let u8arr = new Uint8Array(n);
   while (n--) {
       u8arr[n] = bstr.charCodeAt(n);
   }
   return new Blob([u8arr], { type: mime });
};
 // 上传图片至后台
function apiUpload (filePath) {
  const _this = this;
  api.uploadFile({
    fileVisitPath: filePath,
    type: 13
  }).then(res => {
    const { meetingId, speakerId } = toRefs(props);
    return api.signAgreement({
      fileId: res.data,
      meetingId: meetingId.value,
      speakerId: speakerId.value
    })
  }).then(res => {
    if (!res.code) {
      showToast('签署成功');
      visible.value = false
      emits("submit", `//${filePath}`)
    }
  })
}
function clickSubmit(val) {
  const base64 = val.image
  cors.value.putObject({
    Bucket: corsConfig.bucket,
    Region: corsConfig.region,
    Key: `${corsConfig.key}signature-${new Date().getTime()}.png`,
    Body: dataURLtoBlob(base64),
    onProgress: function (progressData) {
      // console.log(progressData)
    },
  }, (err, data) => {
      if (err) {
        showToast('上传失败，请重新提交')
        return false
      }
      apiUpload(data.Location)
      getCors()
    }
  )
}

function getAuthorization(options, callback) {
  axios
    .get(
      'http://cnf2022adminserver.shanghaistroke-cnf.com/common/tencent/cors/authorization'
    )
    .then((res) => {
      let credentials = res.data.data
      let result = {
        TmpSecretId: credentials.tmpSecretId,
        TmpSecretKey: credentials.tmpSecretKey,
        SecurityToken: credentials.sessionToken,
        // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
        StartTime: credentials.startTime, // 时间戳，单位秒，如：1580000000
        ExpiredTime: credentials.expiredTime, // 时间戳，单位秒，如：1580000000
      }
      this.corsConfig = {
        ...result,
        ...this.corsConfig,
      }
      if (callback) {
        callback(result)
      }
    })
}
function getCors() {
  cors.value = new CORSSDK({
    getAuthorization,
  })
}
function clickClear(val) {}

function clickSign() {}

onMounted(() => {
  getCors()
})
defineExpose({
  init,
})
</script>

<style lang="less" scoped></style>
